package com.tengits.amaplocation;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

/**
 * 灰色保活手法创建的Service进程
 *
 * @author Clock
 * @since 2016-04-12
 */
public class LocationService extends Service {

    private final static String TAG = "AMapLocation";//LocationService.class.getSimpleName();

    private final static int GRAY_SERVICE_ID = -1001;

    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;

    private void startLocation()
    {
        Log.e(TAG, this.getApplicationContext().getPackageName());
        try{
            stopLocation();
            if (null == mLocationClient) {
                mLocationClient = new AMapLocationClient(this.getApplicationContext());
            }

            mLocationOption = new AMapLocationClientOption();

            // 使用连续
            mLocationOption.setOnceLocation(false);
            mLocationOption.setLocationCacheEnable(false);
            // 每4秒定位一次
            mLocationOption.setInterval(10 * 30 * 1000);
            // 地址信息
            mLocationOption.setNeedAddress(false);
            mLocationClient.setLocationOption(mLocationOption);
            mLocationClient.setLocationListener(locationListener);
            mLocationClient.startLocation();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    private void stopLocation() {
        if(mLocationClient != null) {
            mLocationClient.unRegisterLocationListener(locationListener);
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
            mLocationClient = null;
        }
    }

    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    Log.e("AMapGeolocationService", "location");
                    // Toast t = Toast.makeText(LocationService.this,"收到定位信息", Toast.LENGTH_LONG);
                    // t.show();

                    sendGPSOut(amapLocation);
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    // Toast t = Toast.makeText(LocationService.this,"定位失败" + amapLocation.getErrorInfo(), Toast.LENGTH_LONG);
                    // t.show();
                    Log.e("AMapGeolocationService","location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }

        }
    };

    private void sendGPSOut(AMapLocation amapLocation) {
        Intent intent = new Intent(AMapLocationModule.RECEIVER_LOCATION_ACTION);
        intent.putExtra("location", amapLocation);

        sendBroadcast(intent);
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "GrayService->onCreate");
        super.onCreate();
        startLocation();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "GrayService->onStartCommand");
        if (Build.VERSION.SDK_INT < 18) {
            startForeground(GRAY_SERVICE_ID, new Notification());//API < 18 ，此方法能有效隐藏Notification上的图标
        } else {
            Intent innerIntent = new Intent(this, LocationInnerService.class);
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(innerIntent);
            } else {
                startService(innerIntent);
            }
            startForeground(GRAY_SERVICE_ID, getNotification(getApplicationContext()));
        }

        return START_STICKY;
    }

    public  static String notificationId = "superviseID";

    public static String notificationName = "superviseName";

    public static Notification getNotification(Context context){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

            //创建NotificationChannel
            NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH);

            notificationManager.createNotificationChannel(channel);
            Notification.Builder builder = new Notification.Builder(context);
            Intent nfIntent = new Intent();
            builder.setContentIntent(PendingIntent.getActivity(context, 0, nfIntent, 0))
                    .setContentTitle("正在后台定位")
                    .setContentText("定位进行中")
                    .setWhen(System.currentTimeMillis());

            builder.setChannelId(notificationId);

            Notification notification = builder.build();
            notification.defaults = Notification.DEFAULT_SOUND;
            return notification;
        } else {
            return new Notification();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "GrayService->onDestroy");
        super.onDestroy();
        stopLocation();
    }

    /**
     * 给 API >= 18 的平台上用的灰色保活手段
     */
    public static class LocationInnerService extends Service {

        @Override
        public void onCreate() {
            Log.e(TAG, "InnerService -> onCreate");
            super.onCreate();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.e(TAG, "InnerService -> onStartCommand");

            startForeground(GRAY_SERVICE_ID, getNotification(getApplicationContext()));

            //stopForeground(true);
            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }

        @Override
        public IBinder onBind(Intent intent) {
            // TODO: Return the communication channel to the service.
            throw new UnsupportedOperationException("Not yet implemented");
        }

        @Override
        public void onDestroy() {
            Log.e(TAG, "InnerService -> onDestroy");
            super.onDestroy();
        }
    }
}